package com.atguigu.service;

import com.atguigu.DAO.impl.*;
import com.atguigu.pojo.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao=new OrderDaoImp();
    private OrderItemDao orderItemDao=new OrderItemDaoImple();
    private BookDAO bookDAO=new BookDAOImple();

    @Override
    public String createOrder(Cart cart, Integer userId) {
        System.out.println("OrderServiceImpl程序在["+Thread.currentThread().getName()+"]中");

        //订单号===唯一性
        String orderId=System.currentTimeMillis()+""+userId;
        //创建一个订单对象
        Order order=new Order(orderId,new Date(),cart.getTotalPrice(),0,userId);
        //保存订单
        orderDao.saveOrder(order);


        //遍历购物车中的每一个商品项转换成为订单保存到数据库
        for(Map.Entry<Integer,CartItem>entry:cart.getItems().entrySet()){
            //获取每一个购物车中的商品项
            CartItem cartItem=entry.getValue();
            //转化每一个订单项
            OrderItem orderItem=new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId);
            //保存订单到数据库
            orderItemDao.saveOrderItem(orderItem);

            //更新库存和销量
            Book book = bookDAO.queryBookById(cartItem.getId());
            book.setSales(book.getSales()+cartItem.getCount());
            book.setStock(book.getStock()-cartItem.getCount());
            bookDAO.updateBook(book);
        }
        //清空购物车
        cart.clear();
        return orderId;
    }

    @Override
    public List<Order> showAllOrders() {
        List<Order> orders = orderDao.queryOrders();
        return orders;
    }

    @Override
    public int sendOrder(String orderId) {
        int status= orderDao.changeOrderStatus(orderId, 1);
        return status;
    }

    @Override
    public List<OrderItem> showOrderDetails(String orderId) {
        List<OrderItem> orderItems = orderItemDao.queryOrderItemByOrderId(orderId);
        return  orderItems;
    }

    @Override
    public List<Order> showMyOrders(Integer userId) {
        List<Order> orders = orderDao.queryOrderByUserId(userId);
        return orders;
    }

    @Override
    public int receiverOrder(String orderId) {
        int status = orderDao.changeOrderStatus(orderId, 2);
        return status;
    }
}
